import React, { useState ,  lazy , useRef, Suspense } from 'react';
import './webCam.css'
import { useToast , Flex , Button, Img, Badge, Stack, Text, Box, Avatar, CircularProgress} from "@chakra-ui/react"
import AiModal from '../aiModal/aiModal'
import ossClient from '../utils/oss'
import aiRequest  from "../utils/aiRequest";
import { reportData } from "../types/data";
import Camera from '../camera.svg'
// import PhotoCrop from "./PhotoCrop";
const PhotoCrop = lazy(()=>import('./PhotoCrop'))

function WebCam() {
  const toast = useToast()
  const errorToast = (msg:string) => toast({
    title: "ERROR",
    position:'top',
    description: msg,
    status: "error",
    duration: 2000,
    isClosable: true,
  })
  const infoTaost = (msg:string) => toast({
    title: "提示",
    position:'top',
    description: msg,
    status: "info",
    duration: 2000,
    isClosable: true,
  })
  // let dom:HTMLVideoElement|null = null;
  // useEffect(() => {
  //   if (navigator.mediaDevices?.getUserMedia) {
  //     navigator.mediaDevices.getUserMedia({ 
  //       video: { facingMode: 'environment' },
  //       audio: false })
  //       .then(function (stream) {
  //         dom && (dom.srcObject = stream)
  //       })
  //       .catch(err=> {
  //         console.log(err);
  //         errorToast(err)
  //       });
  //   }else{
  //     errorToast("不支持拍照！")
  //   }
  // }); 
  let [isLoading,setLoading] = useState(false);
  let [isInputLoading,setInputLoading] = useState(false);
  let [pickFile,setPickFile] = useState<File|Blob|null>(null)
  const modalRef = useRef<any>(null);
  const [aiInfo,setAiInfo] = useState<reportData|null>(null)

  // function getPhoto(){
  //   if(!dom)return;
  //   setLoading(true)
  //   const { videoHeight ,videoWidth }= dom;
  //   const canvas = document.createElement('canvas');
  //   const ctx = canvas.getContext('2d');
  //   canvas.height = videoHeight;
  //   canvas.width = videoWidth;
  //   ctx?.drawImage(dom, 0, 0,videoWidth,videoHeight);
  //   canvas.toBlob( async (blob) => {
  //     if(!blob)return;
  //     // 拍照上传oss
  //     upload(blob)
  //   });
  // }

  const inputRef = useRef<HTMLInputElement>(null as unknown as HTMLInputElement)
  async function filePick(ev:React.FormEvent<HTMLInputElement>){
    const target  = ev.target as HTMLInputElement;
    const file =  target.files?.[0]
    if(file){
      // await upload(file)
      setPickFile(file)
    }
  }
  async function upload(file:File| Blob ){
    setPickFile(null)
    setLoading(true)
    const url = await ossClient.putPhoto(file)
    infoTaost("图片上传成功，开始打分了")
    console.log(url);
    // 请求ai
    let aiRes = await aiRequest(url)
    // let aiRes = await aiRequest("https://platform-test2.oss-cn-shanghai.aliyuncs.com/panda/2021-10-21/1634803076894.png")
    if(typeof aiRes === 'string'){
      infoTaost(aiRes)
    }else{
      setAiInfo(aiRes);
      modalRef.current.onOpen()
      
    }
    // setInputLoading(false)
    setLoading(false)
  }
  return (
    <>
      {/* <video autoPlay={true} id="videoElement"
        ref={ref=>dom=ref}
      ></video> */}
      <Flex className="bottom-btn" flexDirection="row" alignItems="center" justifyContent="center">
        <Box onClick={() => inputRef.current.click()}>
          <div style={{position:"relative"}}>
            {isLoading && <CircularProgress 
            style={{position:'absolute',top:"-15px",left:"-15px"}} 
            size="210px"  isIndeterminate color="blue.200" />}
            <Avatar bg="blue.100" height="180px" width="180px" p={5} mb={3} src={Camera} ></Avatar>
          </div>
          <Text fontSize="xl" fontWeight="bold">拍照上传 AI点评</Text>
          {/* <Button mr={5} isLoading={isLoading} onClick={getPhoto} colorScheme="blue">📸拍摄</Button> */}
          {/* <Button rounded="full" colorScheme="blue" isLoading={isInputLoading} 
            onClick={() => inputRef.current.click()} > 上传图片</Button> */}
          <input type='file' accept='image/*' ref={inputRef} style={{ display: 'none' }} onInput={filePick}></input>
        </Box>
      </Flex>
      <AiModal ref={ modalRef } paintimg={aiInfo?.paintimg} aiInfo={aiInfo}/>
      <Suspense fallback={
        <Flex className="bottom-btn" flexDirection="row" alignItems="center" justifyContent="center">
          <CircularProgress isIndeterminate size={50} color="blue.200"/>
        </Flex>
      }>
        {pickFile&& <PhotoCrop src={ URL.createObjectURL( pickFile)} onSubmit={upload}></PhotoCrop>}
      </Suspense>
      {aiInfo?<div className="report-warp">
        <Img src={aiInfo.paintimg} width="100vw" height="100vw" objectFit="cover"></Img>
          <Flex justifyContent="center" mt={10}>
          <Stack direction="row">
            <Badge colorScheme="yellow">评分:{aiInfo.score}分</Badge>
            <Badge colorScheme="green">笔画:{aiInfo.strokeRating}分</Badge>
            <Badge colorScheme="red">结构:{aiInfo.structureRating}分</Badge>
            <Badge colorScheme="purple">美观:{aiInfo.beautyRating}分</Badge>
          </Stack>
          </Flex>
          <Flex className="report-warp-btn" justifyContent="center">
            <Button mr={5} onClick={ ()=>setAiInfo(null) } colorScheme="blue">重新拍摄</Button>
            <Button onClick={ ()=>modalRef.current.onOpen() } colorScheme="blue">查看评价</Button>
        </Flex>
      </div>:''}
    </>
  );
}

export default WebCam;
